/**
 * 组织机构选择器
 */
import React from 'react';
import { Spin, Tree } from 'antd';
import { useRequest } from '@/hooks';
import { fetchOrg } from '@/containers/service';

const getTreeData = (
    data = [],
    fieldsName = { value: 'organizationCode', title: 'organizationName' },
    disabledKeys = []
) =>
    data?.map(item => ({
        ...item,
        value: item[fieldsName.value],
        title: item[fieldsName.title],
        key: item[fieldsName.value],
        disabled: disabledKeys.includes(item[fieldsName.value]),
        children: item.children ? getTreeData(item.children, fieldsName, disabledKeys) : item.children
    }));

const FilterOrganization = React.forwardRef(({ value, onChange, requestParams, style, disabledKeys, ...rest }, ref) => {
    const { data, loading } = useRequest(() =>
        fetchOrg({
            organizationPermissions: 1,
            showTreeFlag: 1,
            ...requestParams
        })
    );

    const treeData = React.useMemo(() => {
        const finalData = Array.isArray(data?.data) ? data?.data : [];
        return getTreeData(finalData, undefined, disabledKeys);
    }, [data, disabledKeys]);

    const finalValue = value === '' ? undefined : value;

    return (
        <Spin spinning={loading}>
            {treeData?.length > 0 && (
                <Tree
                    ref={ref}
                    selectedKeys={finalValue}
                    onSelect={onChange}
                    treeData={treeData}
                    defaultExpandParent
                    style={{ paddingLeft: 10, paddingRight: 10, ...style }}
                    dropdownStyle={{ maxHeight: 250, overflowY: 'visible' }}
                    getPopupContainer={trigger => trigger.parentNode}
                    {...rest}
                />
            )}
        </Spin>
    );
});

export default FilterOrganization;
